//
//  ZYCircleHanderView.m
//  YiLin
//
//  Created by Zyark on 2018/6/5.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYCircleHanderView.h"
#import "ZYImageUtils.h"
#define CenterTop               self.frame.size.width/2
#define CenterLeft              self.frame.size.width/2
#define ToRad(deg)              ( (M_PI * (deg)) / 180.0 )
#define ToDeg(rad)              ( (180.0 * (rad)) / M_PI )
#define SQR(x)                  ( (x) * (x) )
#define PL_SLIDER_LINE_WIDTH    8

@interface ZYCircleHanderView()
@property (nonatomic,strong) UIButton *dragButton;
@property (nonatomic,strong) UIPanGestureRecognizer *panGestureRecognizer;
@end

@implementation ZYCircleHanderView{
    CGFloat radius;
}

-(id)initWithFrame:(CGRect)frame{
    if ([super initWithFrame:frame]) {
        if(ZYiPhone5_OR_5c_OR_5s || ZYiPhone4_OR_4s){
            _lineWidth = 10;
        }else{
            _lineWidth = 13;
        }
        _angle = -180;
        radius = self.frame.size.width/2 - _lineWidth;
        CGFloat width = _lineWidth*2.5 + 2;
        _dragButton = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.height/2 -radius - width / 2, self.frame.size.height/2 - width / 2, width, width)];
        [_dragButton setImage:[ZYImageUtils imageWithColor:kCircleSliderColor rect:_dragButton.bounds] forState:UIControlStateNormal];
//        [_dragButton setImage:[UIImage imageNamed:@"round"] forState:UIControlStateNormal];
        _dragButton.layer.cornerRadius = _dragButton.width / 2;
        _dragButton.layer.masksToBounds = YES;
        [self addSubview:_dragButton];
        
        _panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(doDragHandler:)];
        [_dragButton addGestureRecognizer:_panGestureRecognizer];
        
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}



-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    //最外层圆圈
    CGContextAddArc(ctx, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds), radius, 0, M_PI*2, 1);
    [kCircleSliderColor setStroke];
    CGContextSetLineWidth(ctx, 2);
    CGContextSetLineCap(ctx, kCGLineCapButt);
    CGContextDrawPath(ctx, kCGPathStroke);
    
    //内层圆圈
    CGContextAddArc(ctx, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds), radius, 0, M_PI*2, 1);
    [kCircleSliderColor setStroke];
    CGContextSetLineWidth(ctx, 2);
    CGContextSetLineCap(ctx, kCGLineCapButt);
    CGContextDrawPath(ctx, kCGPathStroke);
    
    //上边白色半圆弧
    CGContextAddArc(ctx, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds), radius, 0, M_PI*1, 1);
    [[UIColor whiteColor] setStroke];
    CGContextSetLineWidth(ctx, _lineWidth);
    CGContextSetLineCap(ctx, kCGLineCapButt);
    CGContextDrawPath(ctx, kCGPathStroke);
    
    //绘制背景
    //下面全色半圆弧
    CGContextAddArc(ctx, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds), radius, 0, M_PI*1, 0);
    [kCircleSliderColor setStroke];
    CGContextSetLineWidth(ctx, _lineWidth);
    CGContextSetLineCap(ctx, kCGLineCapButt);
    CGContextDrawPath(ctx, kCGPathStroke);
    
    //绘制拖拽圆弧
    
    //NSLog(@"self.angle %d",self.angle);
    if (self.angle == 180) {
        self.angle = -180;
    }
    CGContextAddArc(ctx, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds), radius, -M_PI, ToRad(self.angle), 0);
    [kCircleSliderColor setStroke];
    CGContextSetLineWidth(ctx, _lineWidth);
    CGContextSetLineCap(ctx, kCGLineCapButt);//设置圆弧两端点的形状，当前为平的
    CGContextDrawPath(ctx, kCGPathStroke);
    
}

/** Given the angle, get the point position on circumference **/
-(CGPoint)pointFromAngle:(NSInteger)angleInt{
    //中心点
    CGPoint centerPoint = CGPointMake(self.frame.size.width/2 - _lineWidth, self.frame.size.height/2 - _lineWidth);
    NSLog(@"centerPoint:%f %f",centerPoint.x,centerPoint.y);
    //根据角度得到圆环上的坐标
    CGPoint result;
    result.y = round(centerPoint.y + radius * sin(ToRad(angleInt)) + _dragButton.width * 0.4) ;
    result.x = round(centerPoint.x + radius * cos(ToRad(angleInt)) + _dragButton.width * 0.4);
    NSLog(@"center:%f %f",result.x,result.y);
    return result;
}


-(void)doDragHandler:(UIPanGestureRecognizer *)recognizer
{
    if(!_dragEnable){
        return;
    }
    if (recognizer.state == UIGestureRecognizerStateEnded) {
//        self.deviceModel = DeviceModelTypeManual;
        if([_delegate respondsToSelector:@selector(circleHanderView:changeTemperature:)]){
            [_delegate circleHanderView:self changeTemperature:_tempureValue];
        }
        if([_delegate respondsToSelector:@selector(circleHanderView:isChangeTemperature:)]){
            [_delegate circleHanderView:self isChangeTemperature:NO];
        }
    }
    else
    {
        if([_delegate respondsToSelector:@selector(circleHanderView:isChangeTemperature:)]){
            [_delegate circleHanderView:self isChangeTemperature:YES];
        }
        CGPoint translation = [recognizer translationInView:self];//相对坐标
        
        //将手势坐标转化为view坐标
        CGPoint recPointer = CGPointMake(recognizer.view.center.x + translation.x,recognizer.view.center.y + translation.y);
        //NSLog(@"translation x = %f,y = %f",recPointer.x,recPointer.y);
        //矫正拖动的坐标到圆形轨迹上面
        CGPoint lastPoint  = [self CirclePoint:radius withCenterCircle:CGPointMake(CenterLeft, CenterTop) withCurrentPoint:recPointer];
        //判断是否超出界限
        if(lastPoint.x > CenterLeft + radius && lastPoint.y > CenterTop){
            return;
        }
        if (lastPoint.x < self.frame.size.width - (CenterLeft - radius) && lastPoint.y > CenterTop) {
            return;
        }
        recognizer.view.center = lastPoint;
        [recognizer setTranslation:CGPointZero inView:self];
        
        
        //计算当前弧度
        CGPoint centerPoint = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
        
        float currentAngle = AngleFromNorth(centerPoint, lastPoint, YES);
        
        //NSLog(@"currentAngle:%f ToRad(self.angle):%f",currentAngle,ToRad(self.angle));
        
        self.angle = floor(currentAngle);
        
        [self setNeedsDisplay];
    }
}

-(CGPoint)CirclePoint:(CGFloat)radius withCenterCircle:(CGPoint)centerCircle withCurrentPoint:(CGPoint)currentPoint
{
    CGPoint cPoint;
    CGFloat x = currentPoint.x;
    CGFloat y = currentPoint.y;
    CGFloat cX ; //圆的X坐标轨迹
    CGFloat cY ; //圆的Y坐标轨迹
    CGFloat daX; // 圆心到转动按钮的距离的平方
    //CGFloat daY;
    CGFloat aX;  // 圆心到转动按钮的距离
    //CGFloat aY;
    CGFloat cosX;  // 圆心水平方向与转动按钮形成的夹角的cos值
    
    //圆心与触控点的距离的平方（勾股定理）
    daX =  (x - centerCircle.x)*(x - centerCircle.x) + (y - centerCircle.y)*(y - centerCircle.y);
    aX = sqrt(daX); //开根号  //圆心与触控点的距离
    
    cosX =  fabs(x - centerCircle.x)/aX;  //绝对值
    cX = cosX*radius ; //  x =R * cosX;  圆心到触控点在水平坐标的X的值
    cY = sqrt(radius*radius - cX*cX);
    
    if(x < centerCircle.x) //如果X所在的点小于圆心 在圆心的左边
    {
        cX = centerCircle.x - cX;
    }
    else
    {
        cX = centerCircle.x + cX;
    }
    
    if(y < centerCircle.y)
    {
        cY = centerCircle.y - cY;
    }
    else
    {
        cY = centerCircle.y + cY;
    }
    cPoint.x = cX;
    cPoint.y = cY;
    return cPoint;
}

//Sourcecode from Apple example clockControl
//Calculate the direction in degrees from a center point to an arbitrary position.
static inline float AngleFromNorth(CGPoint p1, CGPoint p2, BOOL flipped) {
    CGPoint v = CGPointMake(p2.x - p1.x, p2.y - p1.y);
    float vmag = sqrt(SQR(v.x) + SQR(v.y)), result = 0;
    v.x /= vmag;
    v.y /= vmag;
    double radians = atan2(v.y,v.x);
    result = ToDeg(radians);
    return result;
}

//设置当前弧度
-(void)setAngle:(NSInteger)angle
{
    _angle = angle;
    //修复误差，可以拖到最大值
    if (_angle == -1) {
        _angle = 0;
    }
    
    //根据度数，计算温度值
    NSInteger temprange = self.maxTempure - self.minTempure;
    CGFloat addtemp = (float)temprange/180*(180+_angle);
    NSInteger leftValue = (int)addtemp;
    NSInteger rightValue = (addtemp - (int)addtemp)*10;
    
    self.value = self.minTempure + addtemp;
    
    if (rightValue < 5) {
        rightValue = 0;
    }
    else{
        rightValue = 5;
    }
    
//    lblCurTEPMP.text = [NSString stringWithFormat:@"%ld",self.minTempure + leftValue];
//    lblCurTEPMP_dot.text = [NSString stringWithFormat:@"%ld",rightValue];
    
    _tempureValue = self.minTempure + leftValue + (CGFloat)rightValue/10;
}

//设置当前温度
-(void)setTempureValue:(CGFloat)tempureValue
{
    _tempureValue = tempureValue;
    NSInteger temprange = self.maxTempure - self.minTempure;
    
    
    self.angle = (tempureValue - self.minTempure) * 180 / temprange - 180;
    //设置拖拽按钮的位置
    _dragButton.center = [self pointFromAngle:self.angle];
    //进行绘制设定
    [self setNeedsDisplay];
}

//设置是否可以拖拽
-(void)setDragEnable:(bool)dragEnable{
    _dragEnable = dragEnable;
    _panGestureRecognizer.enabled = _dragEnable;
}

@end
